<?php

namespace EasyFeiShu\Authen;

use EasyFeiShu\Core\AbstractAPI;
use Supports\Collection;
use Symfony\Component\HttpFoundation\RedirectResponse;

class Authen extends AbstractAPI
{
    const API_POST_AUTHEN_AUTHORIZE = 'https://open.feishu.cn/open-apis/authen/v1/authorize';
    const API_POST_AUTHEN_ACCESS_TOKEN = 'https://open.feishu.cn/open-apis/authen/v1/access_token';
    const API_POST_AUTHEN_USER_ACCESS_TOKEN = 'https://open.feishu.cn/open-apis/authen/v1/oidc/access_token';
    const API_POST_AUTHEN_REFRESH_ACCESS_TOKEN = 'https://open.feishu.cn/open-apis/authen/v1/refresh_access_token';


    /**
     * 获取授权登录授权码
     * @param string $appId
     * @param string $redirectUri
     * @param string $scope
     * @param string $state
     * @return string
     */
    public function authorize(string $appId, string $redirectUri, string $scope = '', string $state = '')
    {
        if (empty($scope)) {
            $scope = 'contact:contact:readonly_as_app';
        }
        if (empty($state)) {
            $state = 'RANDOMSTATE';
        }

        return self::API_POST_AUTHEN_AUTHORIZE . "?app_id={$appId}&redirect_uri={$redirectUri}&scope={$scope}&state={$state}";
    }

    public function userAccessToken(string $code, string $grantType = 'authorization_code'): Collection
    {
        return $this->parseJSON('post', [
            self::API_POST_AUTHEN_USER_ACCESS_TOKEN,
            [
                'grant_type' => $grantType,
                'code' => $code,
            ],
        ]);
    }

    /**
     * 该接口仅适用于通过网页应用登录方式获取的预授权码
     *
     * @param string $code
     * @param string $grantType
     *
     * @return Collection
     */
    public function accessToken(string $code, string $grantType = 'authorization_code'): Collection
    {
        return $this->parseJSON('post', [
            self::API_POST_AUTHEN_ACCESS_TOKEN,
            [
                'grant_type' => $grantType,
                'code' => $code,
            ],
        ]);
    }

    /**
     * 刷新 access_token.
     *
     * @param string $refreshToken
     * @param string $grantType
     *
     * @return Collection
     */
    public function refreshAccessToken(string $refreshToken, string $grantType = 'refresh_token'): Collection
    {
        return $this->parseJSON('post', [
            self::API_POST_AUTHEN_REFRESH_ACCESS_TOKEN,
            [
                'grant_type' => $grantType,
                'refresh_token' => $refreshToken,
            ],
        ]);
    }
}
